package com.student_exam_system.controller;

import com.student_exam_system.pojo.PaperClass;
import com.student_exam_system.service.PaperClassService;
import com.student_exam_system.service.UserPaperService;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @author fire'ge
 */
@Controller
public class AutoSubmitController {
    final
    UserPaperService userPaperservice;
    final
    PaperClassService  paperClassService;
    ScheduledThreadPoolExecutor scheduled;
    List<PaperClass> paperClasses;

    public AutoSubmitController(@Qualifier("userPaperServiceImpl") UserPaperService userPaperservice, @Qualifier("paperClassServiceImpl") PaperClassService paperClassService) {
        this.userPaperservice = userPaperservice;
        this.paperClassService = paperClassService;
    }

    @PostConstruct
    public void checkSubmitPaper(){
        scheduled = new ScheduledThreadPoolExecutor(10);
        paperClasses = paperClassService
                .queryPaperClassByLessCurrentTime(new Timestamp(System.currentTimeMillis()));
        scheduled.scheduleWithFixedDelay(() -> {
            List<PaperClass> newPaperClasses = paperClassService
                    .queryPaperClassByLessCurrentTime(new Timestamp(System.currentTimeMillis()));

            for (PaperClass paperclass:newPaperClasses) {
                if(!paperClasses.contains(paperclass)){
                    paperClasses.add(paperclass);
                }
            }

        }, 0, 1, TimeUnit.MINUTES);

        scheduled.scheduleWithFixedDelay(() -> {
            long endExamTime;
            for (int i = 0 ; i < paperClasses.size();i++){
                PaperClass paperClass = paperClasses.get(i);
                endExamTime= paperClass.getPcTime().getTime()+paperClass.getPcExamTime()*60L*1000L;

                if (endExamTime<=System.currentTimeMillis()){
                    int update = userPaperservice.updateUserPaperByPaperAndUser(paperClass.getPcPaper(), paperClass.getPcClass());
                    if (update==0){
                        throw new RuntimeException("自动提交试卷失败，请联系管理员");
                    }
                    paperClasses.remove(paperClass);
                }
            }
        }, 0, 1, TimeUnit.SECONDS);

    }

}
